package com.water.quality.testing.controller;

import cn.hutool.core.util.ObjectUtil;
import com.water.quality.testing.common.R;
import com.water.quality.testing.dto.req.UserLoginReqDTO;
import com.water.quality.testing.dto.req.UserModifyReqDTO;
import com.water.quality.testing.dto.req.UserRegisterReqDTO;
import com.water.quality.testing.dto.resp.UserLoginRespDTO;
import com.water.quality.testing.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;


/**
 * 用户请求处理
 */
@RequestMapping
@RestController
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    /**
     * 用户注册
     * @param requestParam  请求参数
     */
    @PostMapping("/api/water/quality/register")
    public R<String> register(@RequestBody UserRegisterReqDTO requestParam){
        try {
            userService.register(requestParam);
            return R.success("注册成功");
        }catch (Throwable ex){
            return R.error("用户名重复，请更换后再试");
        }
    }

    /**
     * 用户登录
     * @param requestParam  请求参数
     */
    @PostMapping("/api/water/quality/login")
    public R<UserLoginRespDTO> login(@RequestBody UserLoginReqDTO requestParam, HttpSession session){
        try {
            UserLoginRespDTO userLoginRespDTO = userService.login(requestParam, session);
            return R.success(userLoginRespDTO);
        }catch (Throwable ex){
            return R.error("用户名或密码错误，请重试");
        }
    }

    /**
     * 修改密码
     * @param requestParam  请求参数
     */
    @PostMapping("/api/water/quality/modify")
    public R<String> modify(@RequestBody UserModifyReqDTO requestParam, HttpSession session){
        // 如果两次输入的修改密码不一致，就返回"两次输入的密码不一致"
        if (!ObjectUtil.equals(requestParam.getPassword(), requestParam.getConfirmPassword())){
            return R.error("两次输入的密码不一致");
        }
        userService.modify(requestParam, session);
        return R.success("修改密码成功");
    }

    /**
     * 退出登录
     */
    @GetMapping("/api/water/quality/logout")
    public R<Void> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success(null);
    }
}
